package cn.bdqn.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.log4j.Log4jImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

@Configuration
public class MybatisConfig {
    @Bean("factoryBean")
    public SqlSessionFactoryBean getFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        try {
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mapper/*.xml"));
            org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
            config.setMapUnderscoreToCamelCase(true);
            config.setAutoMappingBehavior(AutoMappingBehavior.FULL);
            config.setLogImpl(Log4jImpl.class);
            bean.setConfiguration(config);
//          对指定包下的所有类自动起别名，别名规则是类名首字母小写
            bean.setTypeAliasesPackage("cn.bdqn.entity");
            PageInterceptor interceptor = new PageInterceptor();
            Properties properties = new Properties();
            properties.setProperty("helperDialect","mysql");
            properties.setProperty("reasonable","true");
            interceptor.setProperties(properties);
            bean.setPlugins(new Interceptor[]{interceptor});
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return bean;
    }
    @Bean
    public MapperScannerConfigurer getConfigurer() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("cn.bdqn.dao");
        configurer.setSqlSessionFactoryBeanName("factoryBean");
        return configurer;
    }
}
